import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Icon,
    Button,
    Dropdown,
    Menu,
    InputNumber,
    DatePicker,
    Modal,
    message,
    Badge,
    Upload,
    Alert,
    Divider,
    Table,
    Cascader,
    List,
} from 'antd';
import StandardTable from 'components/StandardTable';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/braft.css';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './list.less';
import ListFrom from './listFrom';
import { imgUrl } from '../../services/setting';
import { dateFtt } from '../../utils/utils';
import information from '../../utils/message';

const imgUpdate = `${imgUrl}/v1/platform/common/file/upload/image`;
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const Option = Select.Option;

const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['下架', '上架'];
const ButtonGroup = Button.Group;


function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPG) {
        message.error('请上传JPG/PNG格式');
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
        message.error('上传大小限制为5MB');
    }
    return isJPG && isLt2M;
}
const CreateForm = Form.create()((props) => {
    const {
        modalVisible, form, handleAdd, handleModalVisible, parentBer, loading, grade, series, brand, classify, rich,
        indexUpdate, multipleCancel, multiplePreview, multipleChange, previewVisible, previewImage, editBraft, richEdit,
        dataQuery, memberData, showInventory, cancelInventory, GarlTable, handleSelectRows, handleStandardTableChange,
        searchFormTable, newRows, newInventory, delInventory, inputInventory,
    } = props;
    const datafall = {
        loading,
        dataQuery,
        memberData,
        showInventory,
        cancelInventory,
        GarlTable,
        handleSelectRows,
        handleStandardTableChange,
        searchFormTable,
        newRows,
        addDate: parentBer.specificationsList,
    };
    let { imageUrlBase } = props;
    const grades = [];
    const seriese = [];
    const brands = [];
    let editorInstance = null;
    const editorProps = {
        height: 700,
        contentFormat: 'html',
        initialContent: parentBer.detailInfo,
        contentId: `braft${parentBer.id}`,
        onChange: editBraft,
        extendControls: [
            {
                type: 'split',
            },
            {
                type: 'button',
                text: '预览',
                className: 'preview-button',
                onClick: () => {
                    window.open().document.write(rich);
                },
            },
            {
                type: 'split',
            },
            {
                type: 'button',
                text: '强制所有图片100%',
                className: 'preview-button',
                onClick: () => {
                    const htmlPage = editorInstance.getContent('html');
                    richEdit(htmlPage.replace(/<img/g, '<img style="width: 100%!important"'));
                },
            },
        ],
        media: {
            allowPasteImage: true, // 是否允许直接粘贴剪贴板图片（例如QQ截图等）到编辑器
            image: true, // 开启图片插入功能
            video: true, // 开启视频插入功能
            audio: true, // 开启音频插入功能
            validateFn: (file) => {
                const assi = file.size < 1024 * 1024 * 10;
                if (!assi) message.error('图片超出大小');
                return assi;
            }, // 指定本地校验函数，说明见下文
            uploadFn: (param) => {
                const serverURL = imgUpdate;
                const xhr = new XMLHttpRequest();
                const fd = new FormData();

                // libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
                console.log(param.libraryId);
                const successFn = (response) => {
                    console.log(response);
                    // 假设服务端直接返回文件上传后的地址
                    // 上传成功后调用param.success并传入上传后的文件地址
                    param.success({
                        url: JSON.parse(xhr.responseText).data.pathFull,
                    });
                };

                const progressFn = (event) => {
                    console.log(event, 'event');
                    // 上传进度发生变化时调用param.progress
                    param.progress(event.loaded / event.total * 100);
                };

                const errorFn = (response) => {
                    console.log(response);
                    // 上传发生错误时调用param.error
                    param.error({
                        msg: 'unable to upload.',
                    });
                };

                xhr.upload.addEventListener('progress', progressFn, false);
                xhr.addEventListener('load', successFn, false);
                xhr.addEventListener('error', errorFn, false);
                xhr.addEventListener('abort', errorFn, false);

                fd.append('file', param.file);
                xhr.open('POST', serverURL, true);
                xhr.setRequestHeader('Authorization', sessionStorage.getItem('token'));
                xhr.send(fd);
            },
            removeConfirmFn: null, // 指定删除前的确认函数，说明见下文
            onRemove: null, // 指定媒体库文件被删除时的回调，参数为被删除的媒体文件列表(数组)
            onChange: null, // 指定媒体库文件列表发生变化时的回调，参数为媒体库文件列表(数组)
            onInsert: null, // 指定从媒体库插入文件到编辑器时的回调，参数为被插入的媒体文件列表(数组)
        },
    };
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            if (typeof (fieldsValue.mainImage) !== 'undefined') {
                if (typeof (fieldsValue.mainImage.file.response) !== 'undefined') {
                    prime.mainImage = fieldsValue.mainImage.file.response.data.path;
                } else {
                    delete prime.mainImage;
                }
            }
            if (parentBer.attach.length < 1) {
                message.error('请上传列表图片');
                return;
            }
            for (const item of parentBer.specificationsList) {
                if (item.name === '' || typeof (item.name) === 'undefined') {
                    message.error('请输入别名');
                    return;
                }
            }
            prime.specificationsList = parentBer.specificationsList;
            prime.attach = parentBer.attach;
            form.resetFields();
            handleAdd(prime, parentBer.id);
        });
    };
    const uploadButton = (
        <div>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className="ant-upload-text">Upload</div>
        </div>
    );
    const uploadMultiple = (
        <div>
            <Icon type="plus" />
            <div className="ant-upload-text">Upload</div>
        </div>
    );
    if (props.imageUrlBase === '') imageUrlBase = parentBer.mainImage;
    if (JSON.stringify(grade) !== '{}') {
        grade.content.map((a, b) => (
            grades.push(<Option key={b} value={a.id}>{a.name}</Option>)
        ));
    }
    if (JSON.stringify(series) !== '{}') {
        series.content.map((a, b) => (
            seriese.push(<Option key={b} value={a.id}>{a.name}</Option>)
        ));
    }
    if (JSON.stringify(brand) !== '{}') {
        brand.content.map((a, b) => (
            brands.push(<Option key={b} value={a.id}>{a.name}</Option>)
        ));
    }
    return (
        <Modal
            title={`编辑产品信息---${parentBer.name}`}
            width="90%"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={() => handleModalVisible()}
            destroyOnClose={true}
            maskClosable={false}
        >
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label="首页图片"
                    >
                        {form.getFieldDecorator('mainImage')(
                            <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                headers={{ Authorization: sessionStorage.getItem('token') }}
                                showUploadList={false}
                                action={imgUpdate}
                                beforeUpload={beforeUpload}
                                onChange={indexUpdate}
                            >
                                {imageUrlBase ? <img src={imageUrlBase} alt="" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label="指导价格"
                    >
                        {form.getFieldDecorator('guidePrice', {
                            rules: [{ required: true, message: '请输入指导价格' }],
                            initialValue: parentBer.guidePrice,
                        })(
                            <InputNumber style={{ width: '100%' }}
                                formatter={value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                min={1} placeholder="请输入"
                            />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label="产品系列"
                    >
                        {form.getFieldDecorator('seriesId', {
                            rules: [{ required: true, message: '请选择' }],
                            initialValue: ((typeof (parentBer.series) !== 'undefined') ? parentBer.series.id : ''),
                        })(
                            <Select
                                style={{ width: '100%' }}
                            >
                                {seriese}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label="产品品牌"
                    >
                        {form.getFieldDecorator('brandId', {
                            rules: [{ required: true, message: '请选择' }],
                            initialValue: ((typeof (parentBer.brand) !== 'undefined') ? parentBer.brand.id : ''),
                        })(
                            <Select
                                style={{ width: '100%' }}
                            >
                                {brands}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label="产品等级"
                    >
                        {form.getFieldDecorator('gradeId', {
                            rules: [{ required: true, message: '请选择' }],
                            initialValue: ((typeof (parentBer.grade) !== 'undefined') ? parentBer.grade.id : ''),
                        })(
                            <Select
                                style={{ width: '100%' }}
                            >
                                {grades}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label="产品分类"
                    >
                        {form.getFieldDecorator('asd', {
                            rules: [{ required: true, message: '请选择' }],
                            initialValue: [parentBer.pCategoryId, parentBer.categoryId],
                        })(
                            <Cascader options={classify} placeholder="请选择分类" style={{ width: '100%' }} />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label="是否推荐"
                    >
                        {form.getFieldDecorator('recommend', {
                            rules: [{ required: true, message: '请选择' }],
                            initialValue: parentBer.recommend,
                        })(
                            <Select
                                style={{ width: '100%' }}
                            >
                                <Option value={0}>否</Option>
                                <Option value={1}>是</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label="是否组合"
                    >
                        {form.getFieldDecorator('isSpecial', {
                            rules: [{ required: true, message: '请选择' }],
                            initialValue: parentBer.isSpecial || 0,
                        })(
                            <Select
                                style={{ width: '100%' }}
                            >
                                <Option value={0}>否</Option>
                                <Option value={1}>是</Option>
                            </Select>
                        )}
                    </FormItem>
                </Col>
                <Col md={16} sm={24}>

                    <Col md={24} sm={24}>
                        <FormItem
                            labelCol={{ span: 3 }}
                            wrapperCol={{ span: 19 }}
                            label="列表图片"
                        >
                            {form.getFieldDecorator('attach')(
                                <Upload
                                    action={imgUpdate}
                                    name="file"
                                    listType="picture-card"
                                    fileList={parentBer.attach}
                                    onPreview={multiplePreview}
                                    headers={{ Authorization: sessionStorage.getItem('token') }}
                                    onChange={multipleChange}
                                >
                                    {(parentBer.attach && parentBer.attach.length >= 5) ? null : uploadMultiple}
                                </Upload>
                            )}
                        </FormItem>
                        <Modal visible={previewVisible} footer={null} onCancel={multipleCancel} >
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </Col>
                    <Col md={24} sm={24}>
                        <FormItem
                            labelCol={{ span: 3 }}
                            wrapperCol={{ span: 19 }}
                            label="产品属性"
                        >
                            {form.getFieldDecorator('propertiesList', {
                                initialValue: parentBer.propertiesList,
                            })(<ListFrom />)}
                        </FormItem>
                    </Col>
                    <Divider />
                    <Col md={24} sm={24}>
                        <FormItem
                            labelCol={{ span: 3 }}
                            wrapperCol={{ span: 19 }}
                            label="产品规格"
                        >
                            <List
                                className="demo-loadmore-list"
                                loading={loading}
                                bordered
                                itemLayout="horizontal"
                                header={(
                                    <div>
                                        <div className={styles.danner}>产品名称</div>
                                        <div className={styles.dannerInput}>别名</div>
                                        <div style={{textAlign: 'right'}}><Button type="primary" size="small" onClick={() => {newInventory();}} >新增产品</Button></div>
                                    </div>
                                )}
                                dataSource={parentBer.specificationsList}
                                renderItem={(item, index) => (
                                    <List.Item actions={[<Button  type="danger" size="small" onClick={() => delInventory(item)} key={1}>删除</Button>]}>
                                        <div className={styles.danner}>{item.prodcutName}</div>
                                        <div className={styles.dannerInput}><Input value={item.name} size="small" style={{width: '100%'}} onChange={(e) => inputInventory(e, item, index)} /></div>
                                    </List.Item>
                                )}
                            />
                        </FormItem>
                    </Col>
                    <Col md={24} sm={24}>
                        <FormItem
                            labelCol={{ span: 3 }}
                            wrapperCol={{ span: 19 }}
                            label="商品描述"
                        >
                            {form.getFieldDecorator('descrption', {
                                rules: [{ required: true, message: '请输入商品描述' }],
                                initialValue: parentBer.descrption,
                            })(
                                <TextArea rows={4} />
                            )}
                        </FormItem>
                    </Col>
                </Col>
                <Col md={24} sm={24}>
                    <Card title="产品详情" style={{ width: '100%' }} bodyStyle={{ padding: 0 }}>
                        <BraftEditor {...editorProps} ref={instance => {editorInstance = instance;}} />
                    </Card>
                </Col>
            </Row>
            <EditUser {...datafall} />
        </Modal>
    );
});

const CreateCheck = Form.create()((props) => {
    const { modalVisible, parentBer, handleCheck } = props;
    const priceLevel = ['正价', '特价', '活动款'];
    const columns = [{
        title: '属性名',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '属性值',
        dataIndex: 'value',
        key: 'value',
    }];
    const logs = [
        {
            title: '日志ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '操作用户ID',
            dataIndex: 'userId',
            key: 'userId',
        },
        {
            title: '操作用户名',
            dataIndex: 'userName',
            key: 'userName',
        },
        {
            title: '更新时间',
            dataIndex: 'updateDate',
            key: 'updateDate',
            render: (val) => <span>{dateFtt("yyyy-MM-dd hh:mm:ss", new Date(val))}</span>,
        },
        {
            title: '操作类型',
            dataIndex: 'type',
            key: 'type',
            width: '150px',
            render(val) {
                if (val === 0) {
                    return <Badge status="processing" text="添加" />;
                } else if (val === 1) {
                    return <Badge status="error" text="删除" />;
                } else {
                    return <Badge status="warning" text="编辑" />;
                }
            },
        },
        {
            title: '日志内容',
            dataIndex: 'body',
            key: 'body',
        },
    ];
    let imgs = [];
    if (parentBer.attach) {
        // console.log(parentBer.attach);
        imgs = parentBer.attach || [];
    }
    let proper = [];
    if (parentBer.properties) {
        proper = JSON.parse(parentBer.properties);
    }
    return (
        <Modal
            title={`产品详情---${parentBer.name}`}
            width="80%"
            visible={modalVisible}
            footer={null}
            onCancel={() => handleCheck()}
            destroyOnClose={true}
        >
            <Row gutter={48}>
                <Col span={12}>
                    <ul className={styles.ulCheck}>
                        <li> <p>产品ID</p>
                            {parentBer.id}
                        </li>
                        <li> <p>产品主图</p>
                            <img src={parentBer.mainImage} alt="" style={{ height: '100px' }} />
                        </li>
                        <li> <p>产品列表图</p>
                            <div className={styles.listImg}>
                                {imgs.map((a, b) => {
                                    return (
                                        <img key={b} src={a.url} alt="" />
                                    );
                                })}
                            </div>
                        </li>
                        <li> <p>产品编号</p>
                            {parentBer.code}
                        </li>
                        <li> <p>产品类型</p>
                            {parentBer.type}
                        </li>
                        <li> <p>单位</p>
                            {parentBer.unit}
                        </li>
                        <li> <p>物资标示</p>
                            {parentBer.materialFlag}
                        </li>
                        <li> <p>软体标示</p>
                            {parentBer.softwareFlag}
                        </li>
                        <li> <p>事业部代码</p>
                            {parentBer.businessCode}
                        </li>
                        <li> <p>所属品牌</p>
                            {parentBer.brand ? parentBer.brand.name : ''}
                        </li>
                        <li> <p>所属系列</p>
                            {parentBer.series ? parentBer.series.name : ''}
                        </li>
                        <li> <p>产品等级</p>
                            {parentBer.grade ? parentBer.grade.name : ''}
                        </li>
                    </ul>
                </Col>
                <Col span={12}>
                    <ul className={styles.ulCheck}>
                        <li> <p>是否组合</p>
                            {(parentBer.isSpecial === 0) ? '否' : '是'}
                        </li>
                        <li> <p>价格级别</p>
                            {priceLevel[parentBer.priceGrade]}
                        </li>
                        <li> <p>成本价</p>
                            ￥ {parentBer.costPrice}
                        </li>
                        <li> <p>销售价</p>
                            ￥ {parentBer.salePrice}
                        </li>
                        <li> <p>产品指导价</p>
                            ￥ {parentBer.guidePrice}
                        </li>
                        <li> <p>销量</p>
                            {parentBer.saleNum}
                        </li>
                        <li> <p>上下架</p>
                            {(parentBer.shelfStatus === 0) ? '下架' : '上架'}
                        </li>
                        <li> <p>经销渠道</p>
                            {parentBer.channel20}
                        </li>
                        <li> <p>电商渠道</p>
                            {parentBer.channel40}
                        </li>
                        <li> <p>产品属性</p>
                            <div className={styles.listImg}>
                                <Table dataSource={proper} columns={columns} pagination={false} size="small" />
                            </div>
                        </li>
                        <li> <p>生产周期</p>
                            {parentBer.createPeriod}
                        </li>
                        <li> <p>是否可以下单</p>
                            {parentBer.orderFlag}
                        </li>
                        <li> <p>状态</p>
                            {(parentBer.status === 0) ? '已淘汰' : '逐步淘汰'}
                        </li>
                        <li> <p>分类</p>
                            {parentBer.pCategory ? parentBer.pCategory.name : ''} / {parentBer.category ? parentBer.category.name : ''}
                        </li>

                    </ul>
                </Col>
            </Row>
            <Row>
                <Card style={{ marginTop: '20px' }} title="产品图文详情">
                    <div dangerouslySetInnerHTML={{ __html: parentBer.detailInfo }} style={{ height: '400px', overflowY: 'auto' }}>
                    </div>
                </Card>
            </Row>
            <Row>
                <Card style={{ marginTop: '20px' }} title="产品日志">
                    <Table pagination={false} dataSource={parentBer.logs} columns={logs} rowKey="id" />
                </Card>
            </Row>
        </Modal>
    );
});

const EditUser = Form.create()((props) => {
    const { form, loading, dataQuery, memberData,
        showInventory, cancelInventory, GarlTable, newRows, handleSelectRows,
        handleStandardTableChange, searchFormTable, addDate,
    } = props;

    const memberModal = (e) => {
        form.validateFields(() => {
            form.resetFields();
            cancelInventory(e);
        });
    };

    const GridTableSear = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            GarlTable(prime);
        });
    };
    const srr = (e) => {
        for (const item of addDate) {
            if (item.productId === e.id) {
                return <Button type="primary" disabled>已选择</Button>;
            }
        }
        return <Button type="primary" onClick={() => memberData(e)}>选择</Button>;
    };

    const columnse = [
        {
            title: 'ID',
            width: 70,
            dataIndex: 'id',
        },
        {
            title: '产品编号',
            dataIndex: 'code',
        },
        {
            title: '产品名字',
            dataIndex: 'name',
        },
        {
            title: '操作',
            render: (val, record) => {
                return (
                    <Fragment>
                        <ButtonGroup >
                            {srr(record)}
                        </ButtonGroup>
                    </Fragment>
                );
            },
        },
    ];
    const GridTable = () => {
        return (
            <Row gutter={{md: 8, lg: 24, xl: 48}}>
                <Col md={10} sm={24}>
                    {form.getFieldDecorator('code')(
                        <Input style={{width: '100%'}} placeholder="请输入编号" />
                    )}
                </Col>
                <Col md={10} sm={24}>
                    {form.getFieldDecorator('name')(
                        <Input style={{width: '100%'}} placeholder="请输入名称" />
                    )}
                </Col>
                <Col md={4} sm={24}>
                    <Button icon="search" onClick={GridTableSear} />
                </Col>
            </Row>
        );
    };

    return (
        <Modal
            visible={showInventory}
            onCancel={() => memberModal(false)}
            footer={false}
            header={false}
            width="50%"
            style={{top: '80px'}}
        >
            <Card title={GridTable()}>
                <StandardTable
                    selectedRows={newRows}
                    loading={loading}
                    data={dataQuery.data}
                    columns={columnse}
                    tableSize="small"
                    onSelectRow={handleSelectRows}
                    onChange={handleStandardTableChange}
                    searchForm={searchFormTable}
                    rowKey={record => record.id}
                />
            </Card>
        </Modal>
    );
});


@connect(({ classify, proList, brand, grade, series, loading }) => ({
    proList,
    brand,
    grade,
    series,
    classify,
    loading: loading.models.proList,
}))

@Form.create()

export default class product extends PureComponent {
    state = {
        modalVisible: false,
        modalCheck: false,
        expandForm: false,
        selectedRows: [],
        parentBer: {},
        loading: false,
        imageUrlBase: '',
        previewVisible: false,
        previewImage: '',
        handleButton: '',
        rich: '',
        searchForm: {},
        dataQuery: {},
        showInventory: false,
        searchFormTable: {},
        newRows: [],
    };

    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'brand/fetch',
            payload: {
                page: 1,
                size: 9999,
            },
        });
        dispatch({
            type: 'series/fetch',
            payload: {
                page: 1,
                size: 9999,
            },
        });
        dispatch({
            type: 'grade/fetch',
            payload: {
                page: 1,
                size: 9999,
            },
        });

        dispatch({
            type: 'classify/fetchs',
        });
        this.gainList(1, 10);
        this.gainQuery(1, 10);
    }

    componentWillReceiveProps(val) {
        if (val.proList.mess) {
            if (val.proList.mess.type === 'proList/mess') {
                this.setState({
                    parentBer: val.proList.mess.payload.data,
                    rich: val.proList.mess.payload.data.detailInfo,
                });
                if (this.state.handleButton === 'examine') {
                    this.handleCheck(true);
                } else if (this.state.handleButton === 'compile') {
                    this.handleModalVisible(true);
                }
            }
        }
    }

    gainList = (page, size, data) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'proList/fetch',
            payload: {
                page,
                size,
                data,
            },
        });
    }

    gainQuery = (page, size, data) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'combination/query',
            payload: {
                page,
                size,
                data,
            },
            callback: (data) => this.setState({dataQuery: data}),
        });
    }

    indexUpdate = ({ fileList, file }) => {
        const { status, response } = file;
        const { dispatch } = this.props;
        if (file.response && file.response.code !== 20000) {
            message.error(`${file.response.message},请重新登录`);
            dispatch({ type: 'login/logout' });
        }
        if (status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (status === 'done') {
            this.setState({
                loading: false,
                imageUrlBase: response.data.pathFull,
            });
        }
    }

    handleStandardTableChange = (pagination, filters, sorter) => {
        const data = { ...pagination.searchForm };
        this.gainList(pagination.current, pagination.pageSize, data);
    };

    handleSelectRows = (rows) => {
        this.setState({
            selectedRows: rows,
        });
    };

    toggleForm = () => {
        this.setState({
            expandForm: !this.state.expandForm,
        });
    };

    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
            parentBer: {},
            handleButton: '',
            rich: '',
            imageUrlBase: '',
        });
    };

    handleCheck = (flag) => {
        this.setState({
            modalCheck: !!flag,
            parentBer: {},
            handleButton: '',
            rich: '',
        });
    };

    richEdit = (val) => {
        this.setState({
            rich: val,
        });
    }

    handleAdd = (fields, id) => {
        const parime = {
            ...fields,
            pCategoryId: fields.asd[0],
            categoryId: fields.asd[1],
        };
        delete parime.asd;
        if (parime.propertiesList === null) parime.propertiesList = [];
        parime.detailInfo = this.state.rich;
        const { dispatch } = this.props;
        dispatch({
            type: 'proList/edit',
            payload: {
                ...parime,
                id,
            },
            callback: (data) => {
                information(data);
                this.gainList(this.props.proList.data.page, this.props.proList.data.size, this.state.searchForm);
            },
        });
        this.setState({
            modalVisible: false,
            imageUrlBase: '',
        });
    };

    /* 重置 */
    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({ searchForm: {} });
    };

    handleSearch = (e) => {
        e.preventDefault();

        const { dispatch, form } = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;

            if (fieldsValue.id && fieldsValue.id.toString().length > 10) {
                message.error('id小于等于10位');
                return;
            }
            this.setState({
                searchForm: { ...fieldsValue },
            });
            dispatch({
                type: 'proList/fetch',
                payload: {
                    page: 1,
                    size: this.props.proList.data.size,
                    data: {
                        ...fieldsValue,
                    },
                },
            });
        });
    };

    multipleCancel = () => this.setState({ previewVisible: false });

    multiplePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    };

    multipleChange = (info) => {
        const { dispatch } = this.props;
        const { file, fileList } = info;
        if (file.response && file.response.code !== 20000) {
            message.error(`${file.response.message},请重新登录`);
            dispatch({ type: 'login/logout' });
        }
        const status = file.status;
        const multip = this.state.parentBer;
        if (file.type) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJPG) {
                message.error('请上传JPG/PNG格式');
                return;
            }
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isLt2M) {
                message.error('上传大小限制为5MB');
                return;
            }
        }
        multip.attach = [...fileList];
        if (status === 'done') {
            multip.attach.pop();
            multip.attach = [
                ...multip.attach,
                {
                    uid: file.uid,
                    name: file.response.data.path,
                    url: file.response.data.pathFull,
                    status: 'done',
                },
            ];
        }
        this.setState({ parentBer: multip });
    };

    editBraft = (rawContent) => {
        this.setState({ rich: rawContent });
    };

    memberData = (e) => {
        this.setState({
            parentBer: {
                ...this.state.parentBer,
                specificationsList: [
                    ...this.state.parentBer.specificationsList,
                    {
                        productId: e.id,
                        prodcutName: e.name,
                    },
                ],
            },
        });
    };

    delInventory = (e) => {
        this.setState({
            parentBer: {
                ...this.state.parentBer,
                specificationsList: this.state.parentBer.specificationsList.filter((_) => _.productId !== e.productId),
            },
        });
    };

    inputInventory = (e, item, index) => {
        const arr = this.state.parentBer;
        arr.specificationsList[index].name = e.target.value;
        this.setState({parentBar: {...arr}});
    };

    cancelInventory = (flag) => {
        this.setState({
            showInventory: !!flag,
        });
        this.gainQuery(1,10,{});
    };

    GarlTable = (e) => {
        this.setState({
            searchFormTable: {...e},
        });
        this.gainQuery(1,10,e);
    };

    newStandardTableChange = (pagination) => {
        const data = {...pagination.searchForm};
        this.gainQuery(pagination.current, pagination.pageSize, data);
    };

    newInventory = () => {
        this.setState({
            showInventory: true,
        });
    };

    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={6} sm={24}>
                        <FormItem label="产品ID">
                            {getFieldDecorator('id', {
                                initialValue: '',
                            })(
                                <InputNumber style={{ width: '100%' }} min={1} max={2147483647} placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="产品编号">
                            {getFieldDecorator('code', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="产品名字">
                            {getFieldDecorator('name', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>

                    <Col md={6} sm={24}>
                        <span className={styles.submitButtons}>
                            <Button type="primary" htmlType="submit">查询</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
                            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                                展开 <Icon type="down" />
                            </a>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    renderAdvancedForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={6} sm={24}>
                        <FormItem label="产品ID">
                            {getFieldDecorator('id', {
                                initialValue: '',
                            })(
                                <InputNumber style={{ width: '100%' }} min={1} max={99999999999} placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="产品编号">
                            {getFieldDecorator('code', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="产品名字">
                            {getFieldDecorator('name', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="可否下单">
                            {getFieldDecorator('orderFlag', {
                                initialValue: '',
                            })(
                                <Select placeholder="请选择" style={{ width: '100%' }}>
                                    <Option value="">全部</Option>
                                    <Option value="否">否</Option>
                                    <Option value="是">是</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={6} sm={24}>
                        <FormItem label="状态">
                            {getFieldDecorator('status', {
                                initialValue: '',
                            })(
                                <Select placeholder="请选择" style={{ width: '100%' }}>
                                    <Option value="">全部</Option>
                                    <Option value="0">已淘汰</Option>
                                    <Option value="1">逐步淘汰</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="事业部代码">
                            {getFieldDecorator('businessCode', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="上下架">
                            {getFieldDecorator('shelfStatus', {
                                initialValue: '',
                            })(
                                <Select placeholder="请选择" style={{ width: '100%' }}>
                                    <Option value="">全部</Option>
                                    <Option value="0">下架</Option>
                                    <Option value="1">上架</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <div style={{ overflow: 'hidden' }}>
                    <span style={{ float: 'right', marginBottom: 24 }}>
                        <Button type="primary" htmlType="submit">查询</Button>
                        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
                        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                            收起 <Icon type="up" />
                        </a>
                    </span>
                </div>
            </Form>
        );
    }

    renderForm() {
        return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    render() {
        const {
            selectedRows, modalVisible, parentBer, imageUrlBase, previewVisible, previewImage, modalCheck, rich,
            dataQuery, showInventory, searchFormTable, newRows,
        } = this.state;
        const { proList: { data }, loading, dispatch, grade: { grade }, series: { series }, brand: { brand }, classify: { classify } } = this.props;
        const parentMethods = {
            handleAdd: this.handleAdd,
            handleModalVisible: this.handleModalVisible,
            indexUpdate: this.indexUpdate,
            multipleCancel: this.multipleCancel,
            multiplePreview: this.multiplePreview,
            multipleChange: this.multipleChange,
            editBraft: this.editBraft,
            richEdit: this.richEdit,
            rich,
            parentBer,
            loading,
            imageUrlBase,
            previewVisible,
            previewImage,
            grade,
            series,
            brand,
            classify,
            dataQuery,
            showInventory,
            searchFormTable,
            newRows,
            memberData: this.memberData,
            cancelInventory: this.cancelInventory,
            GarlTable: this.GarlTable,
            handleSelectRows: this.handleSelectRows,
            handleStandardTableChange: this.newStandardTableChange,
            newInventory: this.newInventory,
            delInventory: this.delInventory,
            inputInventory: this.inputInventory,
        };
        const parentCheck = {
            parentBer,
            handleCheck: this.handleCheck,
        };
        const columns = [
            {
                title: 'ID',
                dataIndex: 'id',
                fixed: 'left',
            },
            {
                title: '产品图片',
                dataIndex: 'mainImage',
                width: 150,
                render(val) {
                    if (val === null || val === '') {
                        return (
                            <span>暂未图片</span>
                        );
                    }
                    return (
                        <img src={val} alt="" style={{ height: '50px' }} />
                    );
                },
            },
            {
                title: '产品编号',
                dataIndex: 'code',
                width: 200,
            },
            {
                title: '产品名字',
                dataIndex: 'name',
                width: 300,
            },
            {
                title: '批发价格',
                dataIndex: 'costPrice',
                width: 200,
            },
            {
                title: '销售价格',
                dataIndex: 'salePrice',
                width: 150,
            },
            {
                title: '状态',
                dataIndex: 'shelfStatus',
                width: 150,
                render: (val, record) => {
                    const params = record;
                    const arrey = {
                        id: params.id,
                    };
                    return <a onClick={() => {
                        if (params.shelfStatus === 0) {
                            arrey.shelfStatus = 1;
                        } else {
                            arrey.shelfStatus = 0;
                        }
                        dispatch({
                            type: 'proList/status',
                            payload: arrey,
                            callback: (datas) => {
                                information(datas);
                                this.gainList(this.props.proList.data.page, this.props.proList.data.size, this.state.searchForm);
                            },
                        });
                    }}><Badge status={statusMap[val]} text={status[val]} /></a>;
                },
            },
            {
                title: '可否下单',
                dataIndex: 'orderFlag',
                width: 150,
            },
            {
                title: '品牌',
                dataIndex: 'brand.name',
                width: 150,
            },
            {
                title: '系列',
                dataIndex: 'series.name',
                width: 150,
            },
            {
                title: '等级',
                dataIndex: 'grade.name',
                width: 150,
            },
            {
                title: '库存',
                dataIndex: 'stock',
                width: 150,
            },
            {
                title: '销量',
                dataIndex: 'saleNum',
                width: 150,
            },
            {
                title: '操作',
                fixed: 'right',
                render: (val, record) => (
                    <Fragment>
                        <ButtonGroup>
                            <Button type="ghost" onClick={() => {
                                this.setState({ handleButton: 'compile' });
                                dispatch({
                                    type: 'proList/single',
                                    payload: record,
                                    callback: () => {},
                                });
                            }}>编辑</Button>
                            <Button type="primary" onClick={() => {
                                this.setState({ handleButton: 'examine' });
                                dispatch({
                                    type: 'proList/single',
                                    payload: record,
                                    callback: () => {},
                                });
                            }}>查看</Button>
                        </ButtonGroup>
                    </Fragment>
                ),
            },
        ];
        const scroll = { x: 2335 };
        return (
            <PageHeaderLayout title="产品列表">
                <Card bordered={false}>
                    <div className={styles.tableLists}>
                        <div className={styles.tableListForm}>
                            {this.renderForm()}
                        </div>
                        <StandardTable
                            selectedRows={selectedRows}
                            loading={loading}
                            data={data}
                            columns={columns}
                            scroll={scroll}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleStandardTableChange}
                            searchForm={this.state.searchForm}
                        />
                    </div>
                </Card>
                <CreateForm
                    {...parentMethods}
                    modalVisible={modalVisible}
                />
                <CreateCheck
                    {...parentCheck}
                    modalVisible={modalCheck}
                />
            </PageHeaderLayout>
        );
    }
}

